import numpy as np
from colour import SpectralDistribution, XYZ_to_xy
import colour
def calculate_color_coordinates(wavelength_nm, intensity_mcd):
    """
    根据给定的波长(nm)和发光强度(mcd)计算色域坐标(x, y)。

    参数:
        wavelength_nm (float): 波长，单位为纳米 (nm)
        intensity_mcd (float): 发光强度，单位为毫坎德拉 (mcd)

    返回:
        tuple: 包含两个浮点数的元组，表示色度坐标 (x, y)
    """

    # 创建一个非常简单的光谱功率分布 (SPD)，只有指定波长有非零强度
    wavelengths = np.arange(360, 831, 5)  # 波长范围从360nm到830nm，每隔5nm一个点
    values = np.zeros_like(wavelengths, dtype=float)
    if wavelength_nm in wavelengths:
        values[wavelengths == wavelength_nm] = intensity_mcd

    # 创建光谱分布对象，并假设总发光强度为1来进行归一化
    total_intensity = np.sum(values)
    relative_intensities = values / total_intensity if total_intensity > 0 else values

    sd = SpectralDistribution(dict(zip(wavelengths, relative_intensities)), name=f'{wavelength_nm}nm Light')
    # 使用CIE 1931 2°标准观察者的颜色匹配函数计算XYZ值
#    print(sd)
    XYZ = colour.sd_to_XYZ(sd)
 #   print(XYZ)
    # # 将XYZ值转换为xy色度坐标
    xy = XYZ_to_xy(XYZ / 100)  # 注意：XYZ_to_xy期望输入是归一化后的XYZ值

    return xy

wavelength_nm = [625,545,460]
intensity_mcd = [16.5,75.0,13.5]
# [11,45,7]
# 11/(11 + 45 + 7) * 100.0

for i in range(0,3):
    xy = calculate_color_coordinates(wavelength_nm[i], intensity_mcd[i])
    print(f"Color coordinates for {wavelength_nm}nm with intensity {intensity_mcd} mcd: x={xy[0]:.4f}, y={xy[1]:.4f}")
